﻿using System;
using System.Globalization;
using Artech.EnterLibExt.ExceptionHandling.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Properties;
using Microsoft.Practices.Unity.Utility;

namespace Artech.EnterLibExt.ExceptionHandling
{
    [ConfigurationElementType(typeof(FilterableHandlerData))]
    public class FilterableHandler: IExceptionHandler
    {
        public ExceptionFilterTable FilterTable { get; private set; }

        public FilterableHandler(ExceptionFilterTable filterTable)
        {
            Guard.ArgumentNotNull(filterTable, "filterTable");
            this.FilterTable = filterTable;
        }

        public Exception HandleException(Exception exception, Guid handlingInstanceId)
        {
            string lastHandlerName = String.Empty;
            Exception originalException = exception;
            try
            {
                foreach (IExceptionHandler handler in this.FilterTable.GetExceptionHandlers(exception))
                {
                    lastHandlerName = handler.GetType().Name;
                    exception = handler.HandleException(exception, handlingInstanceId);
                }
            }
            catch
            {              
                throw new ExceptionHandlingException(string.Format(CultureInfo.CurrentCulture, Resources.UnableToHandleException, lastHandlerName));
            }
            return exception;
        }
    }
}
